package com.freestyle.nettychat.chat.attachment;

import com.freestyle.netty.easynetty.codes.CustomFrameEncoder;
import com.freestyle.netty.easynetty.common.Utils;
import com.freestyle.nettychat.chat.dto.AttachmentMessage;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.buffer.Unpooled;
import io.netty.util.ReferenceCountUtil;

/**
 * Created by rocklee on 2022/2/22 9:57
 */
public class AttachmentEncoder extends CustomFrameEncoder<AttachmentMessage> {
  public AttachmentEncoder( byte[] header) {
    super(AttachmentMessage.class, header, attachmentMessage ->{
      byte[] headBytes= Utils.toJsonBytes(attachmentMessage.getProperties());
      ByteBuf buf= Unpooled.buffer().writeInt(headBytes.length);
      try{
        buf.writeBytes(headBytes);
        buf.writeBytes(attachmentMessage.getData());
        return ByteBufUtil.getBytes(buf);
      }
      finally {
        ReferenceCountUtil.release(buf);
      }
    } );
  }
}
